package com.yuandian.management.service.impl;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.net.Ipv4Util;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.management.entity.ConfFilterBusinessData;
import com.yuandian.api.management.entity.ConfOriginalDataFilterVo;
import com.yuandian.management.enums.ProtocolEnum;
import com.yuandian.management.mapper.ConfFilterBusinessDataMapper;
import com.yuandian.management.service.ConfFilterBusinessDataService;
import com.yuandian.management.vo.FilterBusinessDataBodyUpload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 原始数据样包存储表-Service实现
 * @author zfsn
 * @date 2023-4-12
 */
@Slf4j
@Service
public class ConfFilterBusinessDataServiceImpl extends ServiceImpl<ConfFilterBusinessDataMapper, ConfFilterBusinessData>
		implements ConfFilterBusinessDataService {

	@Autowired
	ConfFilterBusinessDataMapper confFilterBusinessDataMapper;

	@Override
	public Map<Integer, Integer> countByFilterIds(List<Integer> ids) {
		List<ConfOriginalDataFilterVo> mapList = confFilterBusinessDataMapper.countByFilterIds(ids);
		Map<Integer, Integer> map = new HashMap<>();
		for (ConfOriginalDataFilterVo stringIntegerMap : mapList) {
			map.put(stringIntegerMap.getFilterId(), stringIntegerMap.getFilterCount());
		}
		return map;
	}

	/**
	 * 分页查询
	 *
	 * @param confFilterBusinessData 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfFilterBusinessData> listPage(ConfFilterBusinessData confFilterBusinessData) {
		List<ConfFilterBusinessData> resultList = new ArrayList<>();
		Page<ConfFilterBusinessData> businessDataPage = null;
		try {
			// 请求ip:端口
			if (!StringUtils.isEmpty(confFilterBusinessData.getRequestIpPort())) {
				String[] requestIpPort = confFilterBusinessData.getRequestIpPort().split(":");
				if (requestIpPort.length > 0) {
					confFilterBusinessData.setRequestIpInt(Ipv4Util.ipv4ToLong(requestIpPort[0]));
				}
				if (requestIpPort.length > 1) {
					confFilterBusinessData.setRequestPort(Integer.parseInt(requestIpPort[1]));
				}
			}
			// 响应ip:端口
			if (!StringUtils.isEmpty(confFilterBusinessData.getResponseIpPort())) {
				String[] responseIpPort = confFilterBusinessData.getResponseIpPort().split(":");
				if (responseIpPort.length > 0) {
					confFilterBusinessData.setResponseIpInt(Ipv4Util.ipv4ToLong((responseIpPort[0])));
				}
				if (responseIpPort.length > 1) {
					confFilterBusinessData.setResponsePort(Integer.parseInt(responseIpPort[1]));
				}
			}
			businessDataPage = confFilterBusinessDataMapper.queryFilterBusinessData(new Page<>(confFilterBusinessData.getPageNum(), confFilterBusinessData.getPageSize()), confFilterBusinessData);
			if (!CollectionUtils.isEmpty(businessDataPage.getRecords())) {
				for (ConfFilterBusinessData businessData : businessDataPage.getRecords()) {
					resultList.add(copyFilterBusinessDataToBaseVo(businessData));
				}
			}
		} catch (Exception e) {
			log.error("查询所有原始包过滤数据错误", e);
		}
		return businessDataPage;
	}

	@Override
	public FilterBusinessDataBodyUpload updateUploadContent(ConfFilterBusinessData confFilterBusinessData) {
		FilterBusinessDataBodyUpload fbdbu = new FilterBusinessDataBodyUpload();
		BeanUtils.copyProperties(confFilterBusinessData, fbdbu);
		if (confFilterBusinessData.getMsgType() == 22) {
			fbdbu.setMsgType("web");
		} else if (confFilterBusinessData.getMsgType() == 23) {
			fbdbu.setMsgType("mid");
		} else if (confFilterBusinessData.getMsgType() == 24) {
			fbdbu.setMsgType("db");
		}
		fbdbu.setDealState(String.valueOf(confFilterBusinessData.getDealState()));
		fbdbu.setProbeTime(confFilterBusinessData.getProbeTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		return fbdbu;
	}



	/**
	 * 替换显示的内容
	 *
	 * @param confFilterBusinessData 查询结果
	 * @return FilterBusinessDataVo
	 */
	private ConfFilterBusinessData copyFilterBusinessDataToBaseVo(ConfFilterBusinessData confFilterBusinessData) {
		if (!StringUtils.isEmpty(confFilterBusinessData.getRequestIp()) && !StringUtils.isEmpty(confFilterBusinessData.getRequestPort())) {
			confFilterBusinessData.setRequestIpPort(Ipv4Util.longToIpv4(Long.parseLong(confFilterBusinessData.getRequestIp())) + ":" + confFilterBusinessData.getRequestPort());
		}
		if (!StringUtils.isEmpty(confFilterBusinessData.getResponseIp()) && !StringUtils.isEmpty(confFilterBusinessData.getResponsePort())) {
			confFilterBusinessData.setResponseIpPort(Ipv4Util.longToIpv4(Long.parseLong(confFilterBusinessData.getResponseIp())) + ":" + confFilterBusinessData.getResponsePort());
		}
		try {
			BASE64Decoder base64 = new BASE64Decoder();
			confFilterBusinessData.setRequestBodyContext(new String(base64.decodeBuffer(confFilterBusinessData.getRequestBodyContext()), "utf-8"));
			confFilterBusinessData.setReqCookieDetail(new String(base64.decodeBuffer(Optional.ofNullable(confFilterBusinessData.getReqCookieDetail()).orElse("")), "utf-8"));
			confFilterBusinessData.setResponseBodyContext(new String(base64.decodeBuffer(confFilterBusinessData.getResponseBodyContext()), "utf-8"));
			confFilterBusinessData.setProtocol(ProtocolEnum.getProtocolEnumValue("" + confFilterBusinessData.getProtocol()));
		} catch (IOException i) {
			throw new UtilException("原始数据包展示与分析,替换显示的内容IO错误");
		}
		return confFilterBusinessData;
	}

}


